<template>
  <div>
    <!-- 顶部栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      autofocus
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 搜索列表 -->
    <van-cell-group>
      <van-cell v-for="(item,index) in showList" :key="index" icon="search"
      @click="$router.push({path:'/searchResult',query:{q:suggestionList[index]} })"
      >
        <template #title>
          <span class="custom-title" v-html="item"></span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from "./home";
export default {
  name: "search",
  data() {
    return {
      value: "",
      suggestionList: [],
      timeID: null
    };
  },
  methods: {
    //   搜索事件，enter触发
    onSearch() {
      console.log(`搜索${this.value}`);
      // 跳转搜索结果页并传参
      this.$router.push({path:'/searchResult',query:{q:this.value}})
    },
    // 输入事件，输入内容变化时触发
    onInput() {
      // 防抖第一步：先清除上一次定时器，以最后一次为准
      clearTimeout(this.timeID);
      // 防抖第二步：开启防抖定时器
      this.timeID = setTimeout(async () => {
        console.log(`输入${this.value}`);
        // 0.非空判断
        if (this.value == "") {
          this.suggestionList = [];
          return;
        }
        // 1.获取推荐词列表
        let res = await getSuggestion(this.value);
        //   console.log(res);
        // 2.绑定数据
        this.suggestionList = res.data.data.options;
      }, 500);
    }
  },
  computed: {
    showList() {
      return this.suggestionList.map(value => {
        let reg = new RegExp(this.value, "ig");
        return value.replace(
          reg,
          match => `<span style='color:red'>${match}</span>`
        );
      });
    }
  }
};
</script>

<style>
</style>